from pptx.util import Inches, Pt
import util,math,sys
from pptx.dml.color import RGBColor
from PIL import Image
import pandas as pd
import numpy as np
from io import BytesIO

def create_layout_ppt(prs,batch,title):
    if len(batch)==0:
        return
    #slide = prs.slides.add_slide(prs.slide_layouts[6])
    slide = prs.slides[0]
    util.add_text_box(slide,0,Inches(4),prs.slide_width,Inches(0.25),title,18,True)
    #获取画布宽高
    slide_height = util.get_slide_height(slide)
    slide_width = util.get_slide_width(slide)
    batch_pd = pd.DataFrame(batch)
    #删除所有空列
    batch_pd = batch_pd.dropna(axis=1,how='all')
    #获取第一行作为标题
    #title = batch_pd.iloc[0].reset_index(drop=True)[0]
    is_bytesio = batch_pd.map(lambda x: isinstance(x, BytesIO))
    #只保留有BytesIO的行
    batch_pd = batch_pd[is_bytesio.any(axis=1)].reset_index(drop=True)
    #删除第一列
    batch_pd = batch_pd.drop(batch_pd.columns[0], axis=1)
    # 删除全是nan的行
    batch_pd = batch_pd.dropna(axis=0,how='all')
    rows,cols = batch_pd.shape
    #增加一行作为标题
    table_top = Inches(2)
    table_left = Inches(0)
    table_width = Inches(slide_width)
    table_height = Inches(slide_height)
    table = slide.shapes.add_table(rows, cols, table_left, table_top, table_width, table_height).table
    util.set_table_background(table)
    cell_width_in = table_width.inches / cols
    cell_height_in = table_height.inches / (rows+1)
    #设置标题
    #table.rows[0].height = Inches(0.01)
    #table.cell(0, 0).merge(table.cell(0, cols-1))
    #table.cell(0, 0).text = title
    #util.set_table_row_font_size(table,0,12)
    #table.rows[0].height = Inches(0.1)
    dpi = 72

    # 数据
    for row in range(rows):
        for col in range(cols):
            cell = table.cell(row, col)
            cell.fill.solid()
            cell.fill.fore_color.rgb = RGBColor(255, 255, 255)   # 设置为白色（透明填充）
            val = batch_pd.iat[row, col]
            if not isinstance(val, BytesIO):
                continue
            img_stream = val
            #重置流位置
            img_stream.seek(0)
            #打开图片
            img = Image.open(img_stream)
            img_width_px, img_height_px = img.size
            # 计算缩放比例
            cell_width_px = cell_width_in * dpi
            cell_height_px = cell_height_in * dpi
            scale = min(cell_width_px / img_width_px, cell_height_px / img_height_px, 1.0)
            img_width_in = (img_width_px * scale) / dpi*0.76
            img_height_in = (img_height_px * scale) / dpi*0.76
            pic_left = table_left.inches + (cell_width_in * col)+ (cell_width_in - img_width_in) / 2
            pic_top = table_top.inches + cell_height_in * (row) + (cell_height_in - img_height_in) / 2 + table.rows[0].height.inches
            slide.shapes.add_picture(img_stream, Inches(pic_left), Inches(pic_top),width=Inches(img_width_in), height=Inches(img_height_in))
            continue